//
//  GGJigsawScrollView.m
//  GGExtension
//
//  Created by yg on 2022/7/27.
//

#import "GGJigsawScrollView.h"

@interface GGJigsawScrollView ()

@property (nonatomic, strong) NSMutableArray <GGJigsawItem *> *items;
@property (nonatomic, assign) CGFloat *contentRulerY;

@end

@implementation GGJigsawScrollView

- (instancetype)initWithFrame:(CGRect)frame{
	if (self = [super initWithFrame:frame]) {
		_scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
		_scrollView.alwaysBounceVertical = YES;
		[self addSubview:_scrollView];

		_contentView = [[UIView alloc] initWithFrame:self.bounds];
		_contentView.backgroundColor = [UIColor grayColor];
		[_scrollView addSubview:_contentView];

		[_scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
	}
	return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
	[self updateItemsFrame];
}

//更新子视图位置
- (void)updateItemsFrame{
	CGPoint contentOffset = _scrollView.contentOffset;//主ScrollView偏移量
}

//布局子视图
- (void)layoutItems{
	CGFloat t = 0;
	for (GGJigsawItem *temp in _items) {
		[self.contentView addSubview:temp.itemView];
		temp.itemView.frame = CGRectMake(0, t, self.frame.size.width, temp.displayHeight);
		t = temp.displayHeight + t;
	}
}

- (void)layoutSubviews{
	[super layoutSubviews];
	_scrollView.frame = self.bounds;
	_contentView.frame = CGRectMake(100, 100, 100, 100);
	[self layoutItems];
}


- (void)addItem:(GGJigsawItem *)item{
	[self.items addObject:item];
}

- (NSMutableArray<GGJigsawItem *> *)items{
	if (_items == nil) {
		_items = [NSMutableArray array];
	}
	return _items;
}

- (void)dealloc{
	if (_scrollView) {
		[_scrollView removeObserver:self forKeyPath:@"contentOffset"];
	}
}

@end

@implementation GGJigsawItem

- (void)setScrollView:(UIScrollView *)scrollView{
	if (_scrollView) {
		[_scrollView removeObserver:self forKeyPath:@"contentSize"];
	}
	_scrollView = scrollView;
	if (_scrollView) {
		[_scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
	}
}

- (void)dealloc{
	if (_scrollView) {
		[_scrollView removeObserver:self forKeyPath:@"contentSize"];
	}
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
	self.scrollHeight = _scrollView.contentSize.height;
	if (self.scrollHeight < self.displayHeight) {
		self.displayHeight = self.scrollHeight;
	}
}

@end
